package com.grm.demo.sisuo;

/**
 * 死锁演示--jconsole定位
 *
 * @author gaorimao
 * @date 2022/04/07
 */
/**
 * 死锁案例
 *
 * @author gaorimao
 * @since 2021-12-10
 */
public class DeadLockDemo implements Runnable {
    public int flag = 1;
    //静态对象是类的所有对象共享的
    private static Object o1 = new Object();
    private static Object o2 = new Object();

    @Override
    public void run() {
        System.out.println("flag=" + flag);
        if (flag == 1) {
            // 锁1
            synchronized (o1) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // 锁2
                synchronized (o2) {
                    System.out.println("1");
                }
            }
        }
        if (flag == 0) {
            // 锁2
            synchronized (o2) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // 锁1
                synchronized (o1) {
                    System.out.println("0");
                }
            }
        }
    }

    public static void main(String[] args) {
        // 线程1，锁1，持有锁2
        DeadLockDemo td1 = new DeadLockDemo();
        td1.flag = 1;
        new Thread(td1).start();
        // 线程2，锁2，持有锁1
        DeadLockDemo td2 = new DeadLockDemo();
        td2.flag = 0;
        new Thread(td2).start();
    }
}
